<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="">
          <el-input v-model="searchInfo.keyWord" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="openDialog">
          新增
        </el-button>
      </div>
      <el-table
        :data="tableData"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="left"
          label="序号"
          min-width="60"
          type="index"
        />

        <el-table-column
          align="left"
          label="节点名称"
          min-width="150"
          prop="NodeName"
          sortable="custom"
        />
        <el-table-column
          align="left"
          label="节点地址"
          min-width="150"
          prop="NodeAddress"
          sortable="custom"
        />
        <el-table-column
          align="left"
          label="管理人员"
          min-width="150"
          prop="NodeUserName"
          sortable="custom"
        >
          <template #default="scope">
            <span
              class="clickable"
              @click="openManagerDialog(scope.row.NodeUserId)"
            >
              {{ scope.row.NodeUserName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="状态"
          min-width="150"
          prop="NodeStatus"
          sortable="custom"
        >
          <template #default="scope">
            <span>{{ scope.row.NodeStatus === 1 ? "在线" : "掉线" }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="硬件信息" min-width="150">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="goToHardware(scope.row.NodeId, scope.row.NodeName)"
            >
              硬件详情
            </el-button>
          </template>
        </el-table-column>

        <el-table-column align="left" label="软件信息" min-width="150">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="goToSoftware(scope.row.NodeId, scope.row.NodeName)"
            >
              软件详情
            </el-button>
          </template>
        </el-table-column>

        <el-table-column align="left" label="运行状况" min-width="150">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="goTorunstate(scope.row.NodeId, scope.row.NodeName)"
            >
              运行状况
            </el-button>
          </template>
        </el-table-column>

        <el-table-column align="left" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button icon="edit" type="primary" link @click="openDetailDialog(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="deleteApiFunc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <!-- 新增节点的模态窗口 -->
    <el-drawer v-model="drawerVisible" title="节点信息" direction="rtl" :size="drawerSize" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 编辑模式下的表单项 -->
        <el-form-item v-if="isEditing" label="节点ID" prop="NodeId">
          <el-input v-model="form.NodeId" placeholder="请输入节点ID" disabled/>
        </el-form-item>
        <el-form-item v-if="isEditing" label="节点名称" prop="nodeName">
          <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item v-if="isEditing" label="节点地址" prop="nodeAddr">
          <el-input v-model="form.nodeAddr" placeholder="请输入节点地址" />
        </el-form-item>
        <el-form-item v-if="isEditing" label="联系人姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入联系人姓名" />
        </el-form-item>
<!--        <el-form-item v-if="isEditing" label="联系人职位" prop="Position">-->
<!--          <el-input v-model="form.Position" placeholder="请输入联系人职位"/>-->
<!--        </el-form-item>-->
        <el-form-item v-if="!isEditing" label="节点名称" prop="nodeName">
          <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item v-if="!isEditing" label="节点地址" prop="nodeAddr">
          <el-input v-model="form.nodeAddr" placeholder="请输入节点地址" />
        </el-form-item>
        <el-form-item v-if="!isEditing" label="节点单位机构" prop="nodeOrganization">
          <el-input v-model="form.nodeOrganization" placeholder="请输入节点单位机构"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="节点运营商" prop="nodeOperator">
          <el-input v-model="form.nodeOperator" placeholder="请输入节点运营商"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="授权码" prop="authorizationCode">
          <el-input v-model="form.authorizationCode" placeholder="请输入授权码"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人联系方式" prop="userContact">
          <el-input v-model="form.userContact" placeholder="请输入联系人联系方式"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人类别" prop="userCategory">
          <el-input v-model="form.userCategory" placeholder="请输入联系人类别"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人账号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="请输入联系人账号" />
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人密码" prop="userPassword">
          <el-input v-model="form.userPassword" placeholder="请输入联系人密码"/>
        </el-form-item>
        <el-form-item v-if="!isEditing" label="联系人职位" prop="Position">
          <el-input v-model="form.Position" placeholder="请输入联系人职位"/>
        </el-form-item>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </el-form>
    </el-drawer>

    <!-- 管理人员信息的模态窗口-->
    <el-dialog v-model="managerDialogVisible" title="管理人员信息" width="30%">
      <el-form label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="managerInfo.name" readonly />
        </el-form-item>
        <el-form-item label="ID">
          <el-input v-model="managerInfo.id" readonly />
        </el-form-item>
        <el-form-item label="职位">
          <el-input v-model="managerInfo.position" readonly />
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="managerInfo.category" readonly />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="managerInfo.contactInfo" readonly />
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="managerInfo.account" readonly />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import {
  getSuperNodeList,
  registerSuperNode,
  getNodeUserInfo,
  deleteNode,
  updataNodeInfo,
} from "@/api/node";

const router = useRouter();
const managerDialogVisible = ref(false);
const managerInfo = ref({
  id: "",
  name: "",
  position: "",
  category: "",
  contactInfo: "",
  account: "",
});
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const searchInfo = ref({
  keyWord: "",
});

const drawerVisible = ref(false);
const drawerSize = ref("40%");
const formRef = ref(null);
const form = ref({
  NodeId: "",
  nodeName: "",
  nodeAddr: "",
  nodeOrganization: "",
  nodeOperator: "",
  authorizationCode: "",
  userName: "",
  userContact: "",
  userCategory: "",
  userAccount: "",
  userPassword: "",
  Position: "",
});
const rules = {
  nodeName: [{ required: true, message: "请输入节点名称", trigger: "blur" }],
  nodeAddr: [{ required: true, message: "请输入节点地址", trigger: "blur" }],
  nodeOrganization: [
    { required: true, message: "请输入节点单位机构", trigger: "blur" },
  ],
  nodeOperator: [
    { required: true, message: "请输入节点运营商", trigger: "blur" },
  ],
  authorizationCode: [
    { required: true, message: "请输入授权码", trigger: "blur" },
  ],
  userName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  userContact: [
    { required: true, message: "请输入联系人联系方式", trigger: "blur" },
  ],
  userCategory: [
    { required: true, message: "请输入联系人类别", trigger: "blur" },
  ],
  userAccount: [
    { required: true, message: "请输入联系人账号", trigger: "blur" },
  ],
  userPassword: [
    { required: true, message: "请输入联系人密码", trigger: "blur" },
  ],
  Position: [
    { required: true, message: "请输入联系人职位", trigger: "blur" },
  ],
};

const isEditing = ref(false);

const getTableData = async () => {
  try {
    const response = await getSuperNodeList(
      page.value,
      pageSize.value,
      searchInfo.value.keyWord
    );
    tableData.value = response.data.NodeList;
    total.value = response.data.TotalNum;
    console.log("Table Data:", tableData.value);
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(() => {
  getTableData();
});

const openDialog = () => {
  isEditing.value = false;
  form.value = {
    NodeId: "",
    nodeName: "",
    nodeAddr: "",
    nodeOrganization: "",
    nodeOperator: "",
    authorizationCode: "",
    userName: "",
    userContact: "",
    userCategory: "",
    userAccount: "",
    userPassword: "",
    Position: "",
  };
  drawerVisible.value = true;
};

const openDetailDialog = (row) => {
  isEditing.value = true;
  form.value = {
    NodeId: row.NodeId,
    nodeName: row.NodeName,
    nodeAddr: row.NodeAddress,
    nodeOrganization: "",
    nodeOperator: "",
    authorizationCode: "",
    userName: row.NodeUserName,
    userContact: "",
    userCategory: "",
    userAccount: "",
    userPassword: "",
    Position: row.NodePosition,
  };
  drawerVisible.value = true;
};

const openManagerDialog = async (userId) => {
  try {
    const response = await getNodeUserInfo(userId);
    managerInfo.value = {
      id: response.data.UserId,
      name: response.data.Name,
      position: response.data.Position,
      category: response.data.Category,
      contactInfo: response.data.ContactInfo,
      account: response.data.Account,
    };
    managerDialogVisible.value = true;
  } catch (error) {
    console.error("获取管理人员信息失败:", error);
    ElMessage.error("获取管理人员信息失败");
  }
};
const resetForm = () => {
  formRef.value.resetFields();
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    console.log("Form Data:", form.value);

    const nodeRegisInfo = {
      NodeId: form.NodeId,
      NodeName: form.value.nodeName,
      NodeAddr: form.value.nodeAddr,
      NodeOrganization: form.value.nodeOrganization,
      NodeOperator: form.value.nodeOperator,
      AuthorizationCode: form.value.authorizationCode,
    };

    const nodeUserRegisInfo = {
      UserName: form.value.userName,
      UserContact: form.value.userContact,
      UserCategory: form.value.userCategory,
      UserAccount: form.value.userAccount,
      UserPassword: form.value.userPassword,
      Position: form.value.Position,
    };

    if (isEditing.value) {
      // Handle update
      const response = await updataNodeInfo({ nodeRegisInfo, nodeUserRegisInfo });
      console.log(response)
      //ElMessage.success("更新成功");
    } else {
      // Handle register
      await registerSuperNode({ nodeRegisInfo, nodeUserRegisInfo });
      ElMessage.success("注册成功");
    }

    drawerVisible.value = false;
    getTableData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

const sortChange = ({ prop, order }) => {
  // 排序逻辑
};

const handleSelectionChange = (selection) => {
  // 选择变化逻辑
};

const handleCurrentChange = (newPage) => {
  page.value = newPage;
  getTableData();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  getTableData();
};

const goTorunstate = (nodeId,NodeName) => {
  console.log("runstate NodeId:", nodeId);
  router.push({ path: "./runstate", query: { nodeId,NodeName } });
};

const goToHardware = (nodeId,NodeName) => {
  console.log("Hardware NodeId:", nodeId);
  router.push({ path: "./hardware", query: { nodeId,NodeName } });
};

const goToSoftware = (nodeId,NodeName) => {
  console.log("Software NodeId:", nodeId);
  router.push({ path: "./software", query: { nodeId,NodeName } });
};

const deleteApiFunc = (row) => {
  ElMessageBox.confirm("确定删除此节点？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteNode(row.NodeId);
        ElMessage.success("删除成功");
        getTableData();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};


const onSubmit = () => {
  // 过滤原始数据
  getTableData();
};

const onReset = () => {
  // 清空搜索框内容
  searchInfo.value.keyWord = "";
  // 重置表格数据为原始数据
  getTableData();
};
</script>

<style scoped lang="scss">
.gva-search-box {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 10px;
}

.gva-pagination {
  margin-top: 20px;
}

.clickable {
  color: rgba(4, 110, 249, 0.664);
  cursor: pointer;
}
</style>